package com.artifex.ebook;

import android.content.Context;
import android.graphics.PixelFormat;
import android.os.Handler;
import android.os.Message;
import android.view.Gravity;
import android.view.WindowManager;
import android.widget.TextView;
import android.widget.Toast;

public class ToastMy {
	public static TextView tv;
	public static WindowManager mWindowManager;
	private static Context m_context;
	private static WindowManager.LayoutParams m_params = new WindowManager.LayoutParams();
	ToastMy(Context context)
	{
		m_context = context;
	}
	public void showMessage(final String msg) {
		showMessage(msg, Toast.LENGTH_SHORT);
	}
	public void showMessage(final int msg) {
		showMessage( m_context.getString(msg), Toast.LENGTH_SHORT);
	}
	public void setGravity(int gravity,int x,int y)
	{
		m_params.gravity = gravity;
		m_params.y = y;
		m_params.x = x;		
	}
	public  void showMessage(String msg,int timems)
	{
		if(timems < 2000)
			timems = 2000;
		mWindowManager=(WindowManager) m_context.getSystemService(Context.WINDOW_SERVICE);
		if(tv==null)
		{
			tv=new TextView(m_context);
			tv.setTextSize(24);
			tv.setTextColor(R.color.narr_text_color);
			tv.setBackgroundColor(R.color.narr_back_color);
			//tv.setBackgroundResource(R.drawable.darkdenim3);
			tv.setPadding(0, 0, 0, 0);
		}
		tv.setText(msg);
		if(tv.getParent()==null)
		{
			m_params.alpha = 1.0f;
			m_params.height = WindowManager.LayoutParams.WRAP_CONTENT;
			m_params.width = WindowManager.LayoutParams.WRAP_CONTENT;
			m_params.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
			| WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE
			| WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON
			| WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN;
			m_params.format = PixelFormat.TRANSLUCENT;
			m_params.windowAnimations = 0;
			mWindowManager.addView(tv, m_params);
			handler.sendEmptyMessageDelayed(101, timems);
		}
		else
		{
			mWindowManager.updateViewLayout(tv, m_params);
			handler.removeMessages(101);
			handler.sendEmptyMessageDelayed(101, timems);
		}
	}


	static Handler handler =new Handler(){
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			if(tv.getParent()!=null)
				mWindowManager.removeView(tv);
		}
	};

	public void cancelCurrentToast()
	{
		if(tv!=null && tv.getParent()!=null)
		{
			mWindowManager.removeView(tv);
			handler.removeMessages(101);
		}
	}
}
